package controller

import (
	"net/http"
	"poker/db"
	"poker/model"
	"poker/utils"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

func GetRank(c *gin.Context) {
	channel := c.Param("channel")
	appid := c.Query("appid")
	top100 := model.GetRankCache().GetTopUsers(channel, appid)
	respData := make([]model.VoteResp, 0)
	for _, user := range top100 {
		voteResp := model.VoteResp{
			Uid:      user.Uid,
			NickName: user.NickName,
			HeadUrl:  user.HeadUrl,
			Score:    user.Score,
			AppID:    user.AppID,
			Voters:   user.Voters,
		}
		respData = append(respData, voteResp)
	}
	c.JSON(http.StatusOK, respData)
}

func GetGirls(c *gin.Context) {
	appid := c.Query("appid")
	filter := bson.M{"appid": appid}
	res := []model.Girl{}
	db.Find("girl", filter, &res)
	c.JSON(http.StatusOK, res)
}

func Vote(c *gin.Context) {
	channel := c.Param("channel")
	var v model.VoteDate
	if err := c.ShouldBindJSON(&v); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data" + err.Error()})
		return
	}

	auth := utils.GenerateAuth(v.Uid + v.AppID + channel)
	// 检查认证信息（这里只是简单示例，实际中需要更复杂的认证逻辑）
	if v.Auth != auth {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid auth"})
		return
	}

	girl := &model.Girl{GID: v.GID, AppID: v.AppID}
	filter := bson.M{"id": girl.GID, "appid": girl.AppID}
	// 调用 FindOne 方法查询用户数据
	girl.FindOne("girl", filter)
	girl.Score += v.Number

	if err := girl.Save("girl", filter); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save girl data"})
		return
	}

	// 更新内存中的排名
	model.GetRankCache().UpdateUserScore(channel, v.AppID, v)

	c.JSON(http.StatusOK, gin.H{"message": "User score updated successfully"})
}
